#!/bin/bash
export 'PS4=[`date +"%Y-%m-%d %H:%M:%S"`]`basename $0`.$LINENO+ '
set -ue
source ../lib/repolib.sh
source ../lib/gitlib.sh
source ../lib/lib.sh
source ./config_obs_common.sh

mytab=`echo -e "\t"`
CPATH=$(cd `dirname $0`;pwd)
service_file_template="$CPATH/service_template/_service"
project_name=""

repo_dir="openeuler_next"
#obs_meta_path="$git_root/obs_meta"
obs_meta_path=$1
if [ ${giteeBranch} == "next" ]; then
    MANIFEST='openeuler_next.xml'
fi
set +u    
if [ "x${team_from_jenkins}" != "x" ]; then
    MANIFEST="openeuler_next_${team_from_jenkins}.xml"
    repo_dir="openeuler_next"
fi


function get_project_name_by_local_path()
{
    local manifest_path=$1
    local local_path=$2
    local res=$(cat ${manifest_path} | grep ${local_path})
    if [ -n "${project_name}" ];then
        return 0
    fi
    if [ -n "${res}" ]; then
        project_name=$(echo ${res} | awk -F 'name="' '{print $2}' | awk -F '"' '{print $1}')
    else
        local res_include=$(cat ${manifest_path} | grep include)
        if [ -n "${res_include}" ]; then
            local str_split=(${res_include})
            for line in ${str_split[@]}
            do
                local tmp=$(echo ${line} | grep name)
                if [ -z "$tmp" ]; then
                    continue
                fi
                local xml_path=$(echo ${line} | awk -F 'name="' '{print $2}' | awk -F '"' '{print $1}')
                get_project_name_by_local_path ${xml_path} ${local_path}
                if [ -n "${project_name}" ]; then
                    break
                fi
            done
        fi
    fi
}

function get_sources()
{
    prj=$1
    pkg=$2
    base_path="$obs_meta_path/projects"

    pkg_service=${base_path}/$prj/$pkg/_service
    index=`cat $pkg_service | egrep -n '<service |</service>' | awk -F':' '{print $1}'`
    index_arry=($index)
    index_num=${#index_arry[@]}
    for((i=0;i<$index_num;i=i+2))
    do
        ((j=$i+1))
        sed -n "${index_arry[$i]},${index_arry[$j]}p" $pkg_service > /tmp/package_service
        scm=`cat /tmp/package_service | egrep 'name="scm"' | egrep -v "<\!--.*-->" | awk -F'<|>' '{print $3}'`
        url=`cat /tmp/package_service | egrep 'name="url"' | egrep -v "<\!--.*-->" | awk -F'<|>' '{print $3}'`
        br=`cat /tmp/package_service | egrep 'name="revision"' | egrep -v "<\!--.*-->" | awk -F'<|>' '{print $3}'`
        set +e
	if [ "$scm" == "repo" ]; then
            l_path=$(echo ${url} | sed "s/${repo_dir}\///")
            current_dir=$(pwd)
            # cd /usr1/jenkins/${repo_dir}/.repo/manifests
            # get_project_name_by_local_path ../manifest.xml ${l_path}
            repo_name=${project_name}
            project_name=""
            cd ${current_dir}
        elif [ "$scm" == "git" -o "$scm" == "svn" ]; then
            repo_name=$url
        fi

        if [ "x$url" != 'x' ];then
            echo "<package name=\"$pkg\" scm=\"$scm\" source=\"$repo_name\" branch=\"$giteeBranch\" tag=\"\" />" >> temp_sources
        fi
    done
}

function update_source_tree()
{
    update_type=$1
    prj=$2
    pkg=$3

    base_path="${git_root}/obs_meta/projects"
    if [ "x$update_type" == "xdel" ]; then
        if [ -f ${base_path}/$prj/.osc/_sources ]; then
            sed -i "/name=\"$pkg\"/d" ${base_path}/$prj/.osc/_sources
        fi
    else
        rm -f temp_sources
        get_sources $prj $pkg
        if [ -f ${base_path}/$prj/.osc/_sources ]; then
            sed -i "/name=\"$pkg\"/d" ${base_path}/$prj/.osc/_sources
        fi
        cat temp_sources >> ${base_path}/$prj/.osc/_sources
    fi
}


function mod_pkg_service()
{
    prj=$1
    pkg=$2
    if ! osc ls $prj $pkg &>/dev/null; then
        log_error "$prj $pkg not found"
    fi
    rm -rf $prj
    osc co $prj $pkg
    cp ${obs_meta_path}/projects/$prj/$pkg/_service $prj/$pkg
    pushd $prj/$pkg
    set +ue
    osc add _service
    set -ue
    osc ci -m "modify by $giteeUserName"
    popd
    update_source_tree 'mod' $prj $pkg
}

function mod_pkg_meta()
{
    prj=$1
    pkg=$2
    if ! osc ls $prj $pkg &>/dev/null; then
        log_error "$prj $pkg not found"
    fi
    if ! osc meta pkg "$prj" "$pkg" --file="${obs_meta_path}/projects/${prj}/${pkg}/.osc/_meta" | grep ^Done.; then
        log_error "${prj}/${pkg}/.osc/_meta deal error"
    fi
}

function mod_prj_meta()
{
    prj=$1
    osc meta prj "$prj" --file="${obs_meta_path}/projects/${prj}/.osc/${prj}.meta" --force
}

function mod_prj_prjconf()
{
    prj=$1
    osc meta prjconf "$prj" --file="${obs_meta_path}/projects/${prj}/.osc/${prj}.prjconf"
}

function find_package()
{
    obs_projects="openEuler:Mainline openEuler:Factory openEuler:20.03:LTS openEuler:20.03:LTS:Extras bringInRely"
    logtype=$1
    prj=$2
    pkg=$3
    if [ "$logtype" == "Add-pkg" ];then
        for p in $obs_projects
        do
            if [ osc ls $p 2>$1 | grep -q -Fx $pkg ];then
                echo "Fail:package $pkg have existed in $p"
                exit 1
            fi
        done
    elif [ "$logtype" == "Del-pkg" ];then
        if [ osc ls $prj 2>&1 | grep -q -Fx $pkg ];then
            echo "$pkg is existed in $prj, can delete it"
        else
            echo "Fail:package $pkg not exist in $prj"
            exit 1
        fi
    fi
}


function parse_git_log()
{
    log_message=$1
    temp_log_type=`echo $log_message | awk '{print $1}'`
    file_path=`echo $log_message | awk '{print $2}'`
    file_name=`basename $file_path`

    prj=`echo $file_path | awk -F'/' '{print $2}'`
    if [ "$file_name" == "_meta" ]; then
        pkg=`echo $file_path | awk -F'/' '{print $3}'`
        if [ "$temp_log_type" == "A" -o "$temp_log_type" == "M" ]; then
            log_type="Mod-pkg-meta"
        else
            log_error "$log_message failed"
        fi
    elif [ "$file_name" == "_service" ]; then
        pkg=`echo $file_path | awk -F'/' '{print $3}'`
        if [ "$temp_log_type" == "A" ]; then
            log_type='Add-pkg'
        elif [ "$temp_log_type" == "D" ]; then
            if test -d ${obs_meta_path}/projects/$prj/$pkg; then
                log_type="Del-pkg-service"
            else
                log_type="Del-pkg"
                pattern_message=`echo $log_message | awk -F'_service' '{print $1}' | sed 's#/#\\\/#g' | sed "s/ /$mytab/g"`
                echo $pattern_message
                sed -i "/$pattern_message/d" $CPATH/diff_patch
                cat $CPATH/diff_patch
            fi
        elif [ "$temp_log_type" == "M" ]; then
            log_type='Mod-pkg-service'
        else
            log_error "$log_message failed"
        fi
    elif [[ "$file_name" == *.prjconf ]]; then
        if [ "$temp_log_type" == "D" ]; then
            log_error "$log_message failed"
        else
            log_type='Mod-prj-prjconf'
        fi
    elif [[ "$file_name" == *.meta ]]; then
        if [ "$temp_log_type" == "D" ]; then
            if test -d ${obs_meta_path}/projects/$prj; then
                log_error "$log_message illegal"
            else
                log_type='Del-prj'
                pattern_message=`echo $log_message | awk -F'.osc' '{print $1}' | sed 's#/#\\\/#g' | sed "s/ /$mytab/g"`
                echo $pattern_message
                sed -i "/$pattern_message/d" $CPATH/diff_patch
                cat $CPATH/diff_patch
            fi
        else
            log_type='Mod-prj-meta'
        fi
    else
        log_error "$log_message failed"
    fi
}
set -e


function check_service_file()
{
    service_file=$1
    service_file_name=$2
    pkg=$3
    tmpfile="./tmpfile"`date +%s%N`
    sed "s/$pkg//g" $service_file > $tmpfile 
    diffnum=`diff -b -B $tmpfile $service_file_template | wc -l`
    if [ $diffnum -ne 0 ];then
       log_info "Fail:service file is illeagl" 
       rm -rf $tmpfile
       exit 1
    fi
    rm -rf $tmpfile
} 


func_main()
{
    check_env
    cd $obs_meta_path
    git diff --name-status HEAD~1 HEAD~0 > $CPATH/diff_patch

    pattern_string="\.meta \.prjconf /_service /_meta"
    for pattern in $pattern_string
    do
        while read line
        do
            if echo "$line" | grep ${pattern}$ ; then
                if echo "$line" | grep _service | grep '\.osc' &>/dev/null; then
                    log_info "illeagl modify,skip ..."
                    continue
                fi
                log_type=''
                prj=''
                pkg=''
                file_path=''
                file_name=''
                parse_git_log "$line"
                check_service_file $"$file_path" "$file_name" "$pkg"
                find_package "$log_type" "$prj" "$pkg"
                #config_obs_by_submit "$log_type" "$prj" "$pkg"
            else
                continue
            fi
        done < $CPATH/diff_patch
    done
    #update_obs_meta 'obs_meta_update' $giteeBranch-$giteePullRequestIid
}

func_main
